package com.jklan.zhiqibackend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jklan.zhiqibackend.dto.request.UploadFileRequest;
import com.jklan.zhiqibackend.entity.Files;
import com.jklan.zhiqibackend.service.FilesService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;

import com.jklan.zhiqibackend.mapper.FilesMapper;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author 30688
 * @description 针对表【files(文件表)】的数据库操作Service实现
 * @createDate 2025-11-06 21:04:00
 */
@Service
public class FilesServiceImpl extends ServiceImpl<FilesMapper, Files>
        implements FilesService {

    /**
     * 文件存储根路径
     */
    @Value("${file.storage.base-path}")
    private String fileStorageBasePath;

    /**
     * 临时文件路径
     */
    @Value("${file.storage.temp-path}")
    private String fileTempPath;
    /**
     * 上传文件
     * 
     * @param request 上传文件请求
     * @return 文件实体
     */
    Files uploadFile(UploadFileRequest request) {
        // 参数校验
        if (request == null || request.getFile() == null || request.getFile().isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }
        // 获取文件信息
        MultipartFile file = request.getFile();
        String fileName = file.getOriginalFilename();
        String fileType = FileNameUtil.extName(fileName);
        // 生成存储信息
        String uuid = IdUtil.randomUUID();
        String fileUploadDay = DateUtil.today();
        String fileUploadPath = fileUploadDay + "/" + uuid + "." + fileType;
        // 上传文件到服务器指定文件
        
        
      
        // 保存文件信息到数据库
        Files filesEntity = new Files();
        filesEntity.setFilename(fileName);
        filesEntity.setOriginalFilename(fileName);
        filesEntity.setFilePath(fileUploadPath);
        filesEntity.setFileSize(file.getSize());
        filesEntity.setFileType(fileType);
        filesEntity.setMimeType(file.getContentType());
        filesEntity.setFileHash(IdUtil.md5Hex(fileUploadPath));
        filesEntity.setRepositoryId(request.getRepositoryId());
        filesEntity.setRepositoryType(request.getRepositoryType());
        filesEntity.setUploaderId(request.getUploaderId());
        filesEntity.setCreatedAt(LocalDateTime.now());
        filesEntity.setUpdatedAt(LocalDateTime.now());
        filesEntity.setIsDeleted(0); // 默认未删除
        baseMapper.insert(filesEntity);
        return filesEntity;
    }
}
